module SortHelper
	
	def sort_link(column, title=nil)
		title ||= column.titleize
		css_class = column == sort_column ? "current #{sort_direction}" : nil
		direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
		link_to title, params.merge(sort_by: column, direction: direction, page: nil), 
			{ class: css_class }
	end
	
	def sort_order(default='', model=nil)
		sort_column(default, model) + ' ' + sort_direction
	end
  
	def sort_column(default='', model=nil)
		# Protect against malicious user input -- only accept what's defined in the options!
		if sort_options.any? { |so| so[:id] == params[:sort_by] } 
			if model != nil and params[:sort_by].include? '#'
				params[:sort_by].gsub('#', model.name.pluralize)
			else
				params[:sort_by]
			end
		else
			default
		end
	end

	# Sanitized against SQL-injection. Only allow "asc" or "desc" as parameter
	def sort_direction
		%w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
	end
	
end
